package com.smartens.boit.util;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;

import com.smartens.boit.R;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class DialogTime extends DialogFragment {

    private static final String TAG = "DialogTime.class";
    private View view;
    private View mDecorView;
    private Animation mIntoSlide;
    private Animation mOutSlide;
    public DialogCallback dialogCallback;
    //过滤重复点击
    private boolean isClick = false;
    private DialogTime.InputHandler mInputHandler = new DialogTime.InputHandler();
    private List<Pickers> firstPickerList;
    private String[] firstPickerId;
    protected String firstSelected;
    protected String thirdSelected;
    private List<Pickers> secondPickerList;
    private List<Pickers> thirdPickerList;
    private List<Pickers> forthPickerList;
    private List<String> secondPickerId;
    private List<String> forthPickerId;
    protected String secondSelected;
    protected String forthSelected;
    //判断用户两次输入的时差是否大于500ms的标志
    private boolean flags = false;
    //第一次的时间
    private long firstTime;
    protected PickerScrollView startHours;
    protected PickerScrollView startMin;
    protected PickerScrollView endHours;
    protected PickerScrollView endMin;
    private TextView cancel;
    private TextView save;

    /**
     * 通讯回调接口
     */
    public interface DialogCallback {
        void confirm(String startHours, String startMin, String endHours, String endMin);

    }


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        view = inflater.inflate(R.layout.dialog_time, container, false);
        startHours = view.findViewById(R.id.start_hour);
        startMin = view.findViewById(R.id.start_min);
        endHours = view.findViewById(R.id.end_hour);
        endMin = view.findViewById(R.id.end_min);
        cancel = view.findViewById(R.id.cancel);
        save = view.findViewById(R.id.save);

        //初始化Dialog
        initDialogView();
        //初始化监听器

        initListener();
        //初始化 pickerView 数据
        initPickerViewData();


        return view;
    }

    protected void initPickerViewData() {
        firstPickerId = new String[]{"00", "01", "02", "03", "04", "05", "06", "07",
                "08", "09", "10", "11", "12", "13", "14", "15", "16",
                "17", "18", "19", "20", "21", "22", "23"};

        firstPickerList = new ArrayList<>();
        thirdPickerList = new ArrayList<>();

        for (int i = 0; i < firstPickerId.length; i++) {
            firstPickerList.add(new Pickers(String.valueOf(firstPickerId[i]), String.valueOf(i)));
            thirdPickerList.add(new Pickers(String.valueOf(firstPickerId[i]), String.valueOf(i)));
        }

        // 设置数据，默认选择
        startHours.setData(firstPickerList);

        startHours.setSelected(0);
        endHours.setData(thirdPickerList);
        endHours.setSelected(0);
        firstSelected = firstPickerId[0];
        thirdSelected = firstPickerId[0];

        secondPickerList = new ArrayList<Pickers>();
        forthPickerList = new ArrayList<Pickers>();

        secondPickerId = new ArrayList<>();
        for (int i = 0; i < 60; i++) {
            if (i < 10) {
                secondPickerId.add("0" + i);
            } else {
                secondPickerId.add(i + "");
            }
        }

        for (String value : secondPickerId) {
            secondPickerList.add(new Pickers(value, value));
            forthPickerList.add(new Pickers(value, value));
        }

        startMin.setData(secondPickerList);
        startMin.setSelected(0);
        endMin.setData(forthPickerList);
        endMin.setSelected(0);
        secondSelected = secondPickerId.get(0);
        forthSelected = secondPickerId.get(0);

    }

    public void setDialogCallback(DialogCallback dialogCallback) {
        this.dialogCallback = dialogCallback;
    }

    /**
     * 根据业务需求，更改弹窗的一些样式
     */
    private void initDialogView() {
        mDecorView = Objects.requireNonNull(getDialog()).getWindow().getDecorView();
        //设置背景为透明
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            mDecorView.setBackground(new ColorDrawable(Color.TRANSPARENT));
        }

        Window window = getDialog().getWindow();
        WindowManager.LayoutParams layoutParams = window.getAttributes();
        //居屏幕底部
        layoutParams.gravity = Gravity.BOTTOM;
        //给window宽度设置成填充父窗体，解决窗体宽度过小问题
        layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;

        window.setAttributes(layoutParams);
        mDecorView.setPadding(0, 0, 0, 0);
        window.getDecorView().setMinimumWidth(getResources().getDisplayMetrics().widthPixels);
    }

    @Override
    public void onViewCreated(@NotNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //弹窗弹入屏幕的动画
        initIntAnimation();
        //初始化监听
        initListener();
        //手指点击弹窗外处理
        touchOutShowDialog();
        //back键处理
        getFocus();
    }

    private void initListener() {
        startHours.setOnSelectListener(firstPickerListener);
        startMin.setOnSelectListener(secondPickerListener);
        endHours.setOnSelectListener(thirdPickerListener);
        endMin.setOnSelectListener(forthPickerListener);
        save.setOnClickListener(clickListener);
        cancel.setOnClickListener(clickListener);

//        dialogDoublePicker.setOnClickListener(clickListener);
//        pickerContainer.setOnClickListener(clickListener);
//        pickerOuter.setOnClickListener(clickListener);
//        dialogBtnContainer.setOnClickListener(clickListener);
//        pickerSelectedBg.setOnClickListener(clickListener);
    }

    class InputHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                confirmButtonClickable();
            }
        }
    }

    private void confirmButtonClickable() {
        flags = true;
        if (System.currentTimeMillis() - firstTime > 500) {
            flags = false;
        } else {
            mInputHandler.sendEmptyMessageDelayed(1, 300);
        }
    }


    /**
     * 弹窗弹入屏幕的动画
     */
    private void initIntAnimation() {
        if (mIntoSlide != null) {
            mIntoSlide.cancel();
        }
        mIntoSlide = new TranslateAnimation(
                Animation.RELATIVE_TO_SELF, 0.0f,
                Animation.RELATIVE_TO_SELF, 0.0f,
                Animation.RELATIVE_TO_SELF, 1.0f,
                Animation.RELATIVE_TO_SELF, 0.0f
        );
        mIntoSlide.setDuration(200);
        mIntoSlide.setFillAfter(true);
        mIntoSlide.setFillEnabled(true);
        view.startAnimation(mIntoSlide);
    }

    /**
     * 过滤重复点击
     */
    public void dismissDialog() {
        if (isClick) {
            return;
        }
        isClick = true;
        initOutAnimation();
    }

    /**
     * 弹窗弹出屏幕的动画
     */
    private void initOutAnimation() {
        if (mOutSlide != null) {
            mOutSlide.cancel();
        }
        mOutSlide = new TranslateAnimation(
                Animation.RELATIVE_TO_SELF, 0.0f,
                Animation.RELATIVE_TO_SELF, 0.0f,
                Animation.RELATIVE_TO_SELF, 0.0f,
                Animation.RELATIVE_TO_SELF, 1.0f);
        mOutSlide.setDuration(200);
        mOutSlide.setFillEnabled(true);
        mOutSlide.setFillAfter(true);
        view.startAnimation(mOutSlide);
        mOutSlide.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                //过滤重复点击的标记
                isClick = false;
                //销毁弹窗
                DialogTime.this.dismiss();
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });

    }

    /**
     * 拦截手势(弹窗外区域)
     */
    @SuppressLint("ClickableViewAccessibility")
    private void touchOutShowDialog() {
        mDecorView.setOnTouchListener((v, event) -> {
            if (event.getAction() == MotionEvent.ACTION_UP) {
                //弹框消失的动画执行相关代码
                dismissDialog();
            }
            return true;
        });
    }

    /**
     * 监听主界面back键
     * 当点击back键时，执行弹窗动画
     */
    private void getFocus() {
        Objects.requireNonNull(getView()).setFocusableInTouchMode(true);
        getView().requestFocus();
        getView().setOnKeyListener((v, keyCode, event) -> {
            // 监听到back键(悬浮手势)返回按钮点击事件
            if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
                //判断弹窗是否显示
                if (Objects.requireNonNull(DialogTime.this.getDialog()).isShowing()) {
                    //关闭弹窗
                    dismissDialog();
                    return true;
                }
            }
            return false;
        });
    }

    /**
     * 选择器选中事件
     */
    private final PickerScrollView.onSelectListener firstPickerListener = new PickerScrollView.onSelectListener() {

        @Override
        public void onSelect(Pickers pickers) {
            firstSelected = pickers.getShowConetnt();
            Log.d(TAG, "onSelect: ");
        }
    };
    private final PickerScrollView.onSelectListener thirdPickerListener = new PickerScrollView.onSelectListener() {

        @Override
        public void onSelect(Pickers pickers) {
            thirdSelected = pickers.getShowConetnt();
        }
    };
    private final PickerScrollView.onSelectListener forthPickerListener = new PickerScrollView.onSelectListener() {

        @Override
        public void onSelect(Pickers pickers) {
            forthSelected = pickers.getShowConetnt();
        }
    };

    private final PickerScrollView.onSelectListener secondPickerListener = new PickerScrollView.onSelectListener() {
        @Override
        public void onSelect(Pickers pickers) {
            secondSelected = pickers.getShowConetnt();
        }
    };

    /**
     * 点击事件
     */
    private final View.OnClickListener clickListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if (v == cancel) {
                dismissDialog();
            } else if (v == save) {
                dialogCallback.confirm(firstSelected, secondSelected, thirdSelected, forthSelected);
            }
//             else if (v == pickerDivide || v == dialogDoublePicker || v == dialogBtnContainer || v == pickerContainer || v == pickerOuter) {
//            }
        }

    };
}
